/*
 * CCVisu is a tool for visual graph clustering
 * and general force-directed graph layout.
 * This file is part of CCVisu.
 *
 * Copyright (C) 2005-2011  Dirk Beyer
 *
 * CCVisu is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * CCVisu is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with CCVisu; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Please find the GNU Lesser General Public License in file
 * license_lgpl.txt or http://www.gnu.org/licenses/lgpl.txt
 *
 * Dirk Beyer    (firstname.lastname@uni-passau.de)
 * University of Passau, Bavaria, Germany
 */
package org.sosy_lab.ccvisu.readers;

import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;

import org.sosy_lab.ccvisu.CCVisuController;
import org.sosy_lab.ccvisu.graph.GraphData;
import org.sosy_lab.ccvisu.graph.GraphEdge;
import org.sosy_lab.ccvisu.graph.GraphVertex;
import org.sosy_lab.ccvisu.graph.Relation;
import org.sosy_lab.ccvisu.graph.Tuple;
import org.sosy_lab.common.LogManager;

/**
 * Reader for input graphs.
 * Different concrete graph readers return what they read in String format
 * (list of edges of type <code>GraphEdgeString</code>)
 * when <code>readEdges()</code> is called.
 * One single transformation method (<code>readGraph()</code> of this class)
 * transforms the string representation into the final format
 * (<code>GraphData</code> object with edges of type <code>GraphEdgeInt</code>).
 */
public abstract class ReaderDataGraph extends ReaderData {

  /** End of line.*/
  protected final static String endl = CCVisuController.endl;

  /**
   * Constructor.
   * @param reader  Stream reader object.
   */
  public ReaderDataGraph(LogManager logger, BufferedReader reader) {
    super(logger, reader);
  }

  /**
   * Reads the edges of a graph from stream reader <code>reader</code>,
   * and stores them in a list (of <code>GraphEdgeString</code> elements).
   * @return List of string edges.
   */
  abstract protected Relation readTuples();

  /**
   * Reads the graph data from stream reader <code>reader</code>.
   * @param graph  <code>GraphData</code> object to store the graph data in.
   */
  @Override
  public void read(GraphData graph) {
    assert(graph != null);

    graph.setRelation(readTuples());

    // Initialize graph representation.
    initializeGraph(graph); // TODO: move to GraphData
  }

  /**
   * Reads the graph data from list of string edges (see class comment).
   */
  private void initializeGraph(GraphData graph) {
    List<GraphVertex> vertices = new ArrayList<GraphVertex>();

    // Maps a vertex name to a GraphVertex.
    Map<String, GraphVertex> nameToVertex = new HashMap<String, GraphVertex>();

    int lineNr = 0;
    for (Tuple tuple : graph.getRelation()) {
      lineNr++;
      try {
        List<String> adTuples = tuple.getTupleElements();
        if (adTuples.size() < 2) {
          logger.log(Level.WARNING, "Runtime error: Exception while reading "
              + "a graph edge, at line " + lineNr + ":");
          logger.log(Level.WARNING, "Input graph file needs to follow the RSF format");
          logger.log(Level.WARNING, "'<graph-name> <source-vertex> <target-vertex> [<weight>]'.");
        }

        // Relation name.
        String edgeRelName = tuple.getRelationName();
        // Source vertex.
        String edgeSource = adTuples.get(0);
        // Target vertex.
        String edgeTarget = adTuples.get(1);
        // Edge weight.
        String edgeWeight = "1.0";

        if (adTuples.size() > 2) {
          edgeWeight = adTuples.get(2);
        }

        GraphVertex source = createOrReturnVertex(vertices, nameToVertex, edgeSource);
        source.setIsSource(true);

        GraphVertex target = createOrReturnVertex(vertices, nameToVertex, edgeTarget);

        float weight = 1.0f;
        try {
          weight = Math.abs(Float.parseFloat(edgeWeight));
        } catch (Exception e) {
          logger.log(Level.WARNING, "RSF warning (if input is a weighted graph): "
              + "Float expected for relation '" + edgeRelName + "' at '"
              + edgeWeight + "', at line " + lineNr + ".");
          logger.logUserException(Level.FINEST, e, "see message 'RSF warning'");
          weight = 1.0f;
        }

        // Insert edge to graph.
        // (Detection of reflexive edges is done by CCVisu.computeLayout().)
        GraphEdge edge = new GraphEdge(edgeRelName, source, target, weight);
        graph.addEdge(edge);

        if (edge.getWeight() < 0) {
          logger.log(Level.WARNING, "Invalid graph: edge {" + source.getName()
              + "," + target.getName() + "} " + "has weight: " + edge.getWeight() + ".");
        }
      } catch (Exception e) {
        // TODO: improve message; I don't know what happens here
        logger.logUserException(Level.WARNING, e, "something went wrong, but we ignore it after all");
      }
    }
    graph.setVertices(vertices);
  }

  private GraphVertex createOrReturnVertex(List<GraphVertex> vertices,
      Map<String, GraphVertex> nameToVertex, String vertexName) {

    if (nameToVertex.containsKey(vertexName)) {
      // Vertex already exists
      return nameToVertex.get(vertexName);

    } else{
      // Insert vertex into graph.
      GraphVertex source = new GraphVertex(vertexName, vertices.size());
      vertices.add(source);
      nameToVertex.put(vertexName, source);
      return source;
    }
  }
}
